<?php

set_include_path('../');

require_once('show/show.php');
require_once('database/database.php');

require_once('registry.php');

require_once('model/model.php');
require_once('model/column.php');
require_once('model/record.php');
require_once('model/recordset.php');

//$db = new database('localhost', 'root', '', 'rephp');
$db = new database('192.168.210.61', 'root', 'myroot', 'rephp');
$db->debug = true;

registry::getInstance()->db = $db;
registry::getInstance()->models = new stdClass();

class User extends model
{
	var $relations = array(
		array(
			'type' => 'one',
			'model' => 'Profile',
			
			'local' => 'profile_id',
			'foreign' => 'id',
			
			'as' => 'Profile',
			'recursion' => 1
		),
		array(
			'type' => 'many',
			'model' => 'Post',
			
			'local' => 'id',
			'foreign' => 'user_id',
			
			'as' => 'Posts',
			'recursion' => 3
		)
	);
};

class Post extends model{
	
	var $relations = array(
		array(
			'type' => 'one',
			'model' => 'User',
			
			'local' => 'user_id',
			'foreign' => 'id',
			
			'as' => 'User',
			'recursion' => 0
		),
		array(
			'type' => 'many',
			'model' => 'Comment',
			
			'local' => 'id',
			'foreign' => 'post_id',
			
			'as' => 'Comments',
			'recursion' => 2
		)
	);
	
};

class Profile extends model{
	
	var $relations = array(
		array(
			'type' => 'many',
			'model' => 'User',
			
			'local' => 'id',
			'foreign' => 'profile_id',
			
			'as' => 'Users',
			'recursion' => 1
		)
	);
};

class Comment extends model{
	
	var $relations = array(
		array(
			'type' => 'one',
			'model' => 'User',
			
			'local' => 'user_id',
			'foreign' => 'id',
			
			'as' => 'User',
			'recursion' => 0
		)
	);
	
};

$user = new User();
$post = new Post();
$profile = new Profile();
$comment = new Comment();

$allUsers = $user->findAllBy();

show($allUsers);

echo '<pre>';
echo "----------------------------------------------------------------<br/>";
foreach($allUsers as $u)
{
	echo "<b>Username</b>: " . $u->username . "<br/>";
	echo " + <b>Profile name</b>: " . $u->Profile->name . "<br/>";
	echo " + <b>Posts</b>: <br/>";
	foreach($u->Posts as $post)
	{
		echo " +-- <b>Post title</b>: " . $post->title . "<br/>";
		if(count($post->Comments))
		{
			echo " |   + <b>Comments</b>: <br/>";
			foreach($post->Comments as $comment)
			{
				echo " |   | + <b>Comments title</b>: " . $comment->title . "<br/>";
				echo " |   |   + <b>Comment posted by user</b>: " . $comment->User->username . "<br/>";
			}
		}
	}
	echo "----------------------------------------------------------------<br/>";
}
echo '</pre>';

showMemoryUsage();
?>